package yang.yu.sunny.service.impl;

import org.dayatang.utils.BeanUtils;
import yang.yu.sunny.domain.sales.OrderItem;
import yang.yu.sunny.domain.sales.OrderItems;
import yang.yu.sunny.infra.elasticsearch.ProductCategorySearcher;
import yang.yu.sunny.infra.elasticsearch.ProductSearcher;
import yang.yu.sunny.service.OrderItemDto;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by yyang on 16/4/11.
 */
public class OrderItemAssembler {

    private ProductCategorySearcher categorySearcher;
    private ProductSearcher productSearcher;

    private Map<Long, String> categoryMap;
    private Map<Long, String> productMap;


    public OrderItemAssembler(ProductCategorySearcher categorySearcher,
                              ProductSearcher productSearcher) {
        this.categorySearcher = categorySearcher;
        this.productSearcher = productSearcher;
    }

    public OrderItemDto toDto(OrderItem item) {
        OrderItemDto result = new OrderItemDto();
        new BeanUtils(result).copyPropertiesFrom(item);
        result.setProductName(productMap.get(item.getProductId()));
        result.setCategoryName(categoryMap.get(item.getCategoryId()));
        return result;
    }

    public List<OrderItemDto> toDto(List<OrderItem> items) {
        OrderItems orderItems = OrderItems.of(items);
        productMap = productSearcher.namesOf(orderItems.products());
        categoryMap = categorySearcher.namesOf(orderItems.categories());
        return items.stream().map(this::toDto).collect(Collectors.toList());
    }
}
